<?php

namespace app\common\model;

use think\Db;
use think\Model;

class Ad extends Model
{
    // 表名
    protected $name = 'ad';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = false;

    // 定义时间戳字段名
    protected $createTime = false;
    protected $updateTime = false;
    
    // 追加属性
    protected $append = [
        'begin_time_text',
        'end_time_text',
	    'type_text'
    ];
    
	
    const TYPE_GOODS = 1;
    const TYPE_CATE = 2;
    const TYPE_ARTICLE = 3;
    
    
    public $typeList = [
        self::TYPE_GOODS => '商品详情',
	    self::TYPE_CATE => '分类商品列表',
	    self::TYPE_ARTICLE => '文章详情'
    ];
    
	public function getTypeTextAttr($value, $data) {
		$value = $value ? $value : $data['ad_type'];
		$list = self::$typeList;
		return isset($list[$value]) ? $list[$value] : '';
	}


    public function getBeginTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['begin_time']) ? $data['begin_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getEndTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['end_time']) ? $data['end_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    protected function setBeginTimeAttr($value)
    {
        return $value && !is_numeric($value) ? strtotime($value) : $value;
    }

    protected function setEndTimeAttr($value)
    {
        return $value && !is_numeric($value) ? strtotime($value) : $value;
    }
    
    public function position(){
		return $this->belongsTo('adPosition', 'position_id', 'id', '', 'left')->setEagerlyType(0);
    }
	
	/**
	 * 根据分类获取轮播图
	 * @param $id 位置ID
	 * @return false|\PDOStatement|string|\think\Collection
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\ModelNotFoundException
	 * @throws \think\exception\DbException
	 */
    public function getAdById($id) {
    	$where = [
    	    'position_id' => $id,
		    'begin_time' => ['elt', time()],
		    'end_time' => ['egt', time()]
	    ];
    	$rows = Db::name('ad')->where($where)
		    ->field('id, image, name, param, ad_type')
		    ->order(['sort' => 'ASC'])
		    ->select();
    	return $rows;
    }

}
